package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.po.Account;
import com.itheima.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * ClassName:AccountServiceImpl
 * Package:com.itheima.service.impl
 * Description:账户的业务层实现类
 * <p>
 * 事务控制应该全都在业务层
 * Date:2020/2/21 15:14
 * User: snow
 */
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS , readOnly = true)//只读型事务配置
public class AccountServiceImpl implements AccountService {
	@Resource(name = "accountDao")
	private AccountDao accountDao;


	public Account findAccountById(Integer id) {
		Account account = accountDao.findAccountById(id);
		return account;
	}

	public Account findAccountByName(String accountName) {
		Account account = accountDao.findAccountByName(accountName);
		return account;
	}


	public void updateAccount(Account account) {
		accountDao.updateAccount(account);
	}


	//需要读写型事务配置
	@Transactional(propagation = Propagation.REQUIRED ,readOnly = false)
	public void transfer(String sourceName, String targetName, Float money) {
		// 根据名称查询转出账户
		Account source = accountDao.findAccountByName(sourceName);
		// 根据名称查询转入账户
		Account target = accountDao.findAccountByName(targetName);
		// 转出账户数据操作
		source.setMoney(source.getMoney() - money);
		// 转入账户数据操作
		target.setMoney(target.getMoney() + money);
		// 更新转出账户
		accountDao.updateAccount(source);
		// int i = 1 / 0;
		// 更新转入账户
		accountDao.updateAccount(target);
	}
}
